package com.test.QtestServer.interceptors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.test.QtestServer.pojo.Tokens;
import com.test.QtestServer.service.TokenService;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;
    
    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception{
        String token = request.getHeader("Authorization");
        try{
            if(token==null){
                throw new Exception();
            }
            //TODO: 从数据库中查询超时时间内token是否存在
            Tokens tokenInDB = tokenService.findActiveToken(token);
            if(tokenInDB==null){
                throw new Exception();
            }
            return true;
        }catch (Exception e) {
            response.setStatus(401);
            return false;
        }
        
    }
}
